package com.example.springboot_test.design_mode.proxy.virtual_proxy;

import javax.swing.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;

public class ImageProxyTestDrive {
    ImageComponent imageComponent;
    JFrame jFrame = new JFrame("CD cover");
    JMenuBar menuBar;
    JMenu menu;
    Hashtable hashtable = new Hashtable();

    public static void main(String[] args) throws Exception {
//        ImageProxyTestDrive imageProxyTestDrive = new ImageProxyTestDrive();
        System.out.println("hello world");
    }

    public ImageProxyTestDrive() throws MalformedURLException {
        hashtable.put("hello", "https://hao123.com");
        hashtable.put("github", "https://github.com");
        hashtable.put("gitee", "https://gitee.com");

        URL url = new URL(hashtable.get("hello").toString());
        menuBar = new JMenuBar();
        menu = new JMenu("Favorite CDs");
        menuBar.add(menu);
        jFrame.setJMenuBar(menuBar);

        for (Enumeration e = hashtable.elements(); e.hasMoreElements(); ) {
            String name = (String) e.nextElement();
            JMenuItem item = new JMenuItem(name);
            menu.add(item);
            item.addActionListener((a) -> {
                imageComponent.setIcon(new ImageProxy(initUrl(a.getActionCommand())));
            });

        }
        Icon icon = new ImageProxy(url);
        imageComponent = new ImageComponent(icon);
        jFrame.getContentPane().add(imageComponent);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setSize(800, 600);
        jFrame.setVisible(true);
    }

    private URL initUrl(String name) {
        try {
            return new URL((String) hashtable.get(name));
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }

    }


}
